/**
 * Created by jiachenpan on 16/11/18.
 */
import { Message } from 'element-ui'
// 时间格式化
export function parseTime (time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const timeStr = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    if (key === 'a') {
      return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return timeStr
}

export function formatTime (time, option) {
  time = +time * 1000
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
            1 +
            '月' +
            d.getDate() +
            '日' +
            d.getHours() +
            '时' +
            d.getMinutes() +
            '分'
    )
  }
}

export function objectMerge (target, source) {
  /* Merges two  objects,
         giving the last one precedence */

  if (typeof target !== 'object') {
    target = {}
  }
  if (Array.isArray(source)) {
    return source.slice()
  }
  Object.keys(source).forEach(property => {
    const sourceProperty = source[property]
    if (typeof sourceProperty === 'object') {
      target[property] = objectMerge(target[property], sourceProperty)
    } else {
      target[property] = sourceProperty
    }
  })
  return target
}

export function cloneObject (target, source) {
  if (typeof target !== 'object') {
    target = {}
  }
  Object.keys(target).forEach(property => {
    const sourceProperty = source[property]
    target[property] = sourceProperty
  })
  return target
}

export function reolveTime (timeStr) {
  timeStr = timeStr.split('.')[0]
  timeStr = timeStr.replace('-', '/')
  timeStr = timeStr.replace('-', '/')
  timeStr = timeStr.replace('T', ' ')
  var time = new Date(timeStr)
  return time
}

// 通用导出数据
export async function exportData (fun, query, limit = 5000, reCall = false) {
  if (!reCall) {
    query = Object.assign({}, query)
    query.start = 1
    query.act = 'export'
    query.limit = parseInt(limit)
    query.type = 'page'
  }
  try {
    const result = await fun(query)

    if (result.count === 0) {
      Message.error('暂无数据，无法导出')
    } else {
      //    window.open('/api' + result)
      funDownload('/api' + result)
    }
  } catch (error) {
    //  console.log('error', error)
    if (error.status === 2) {
      query.start = error.data.start
      exportData(fun, query, parseInt(limit), true)
    }
  }
}
export function funDownload (contentUrl) {
  // 创建隐藏的可下载链接
  var eleLink = document.createElement('a')
  eleLink.style.display = 'none'
  eleLink.href = contentUrl
  // 触发点击
  document.body.appendChild(eleLink)
  eleLink.click()
  // 然后移除
  document.body.removeChild(eleLink)
}

export function split (arrStr, fix = ',') {
  const arr = arrStr.split(fix)
  return arr.filter(e => e !== '')
}

export function mergeArray (arr1, arr2, prop = 'value') {
  for (let i = 0; i < arr1.length; i++) {
    for (let j = 0; j < arr2.length; j++) {
      if (prop) {
        if (arr1[i][prop] === arr2[j][prop]) {
          arr1.splice(i, 1) // 利用splice函数删除元素，从第i个位置，截取长度为1的元素
        }
      } else {
        if (arr1[i] === arr2[j]) {
          arr1.splice(i, 1) // 利用splice函数删除元素，从第i个位置，截取长度为1的元素
        }
      }
    }
  }
  for (let i = 0; i < arr2.length; i++) {
    arr1.push(arr2[i])
  }
  return arr1
}

// 根据数组对象属性值排序
export function compare (property) {
  return function (obj1, obj2) {
    var val1 = obj1[property]
    var val2 = obj2[property]
    if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
      val1 = Number(val1).toLowerCase()
      val2 = Number(val2).toLowerCase()
    }
    if (val1 < val2) {
      return -1
    } else if (val1 > val2) {
      return 1
    } else {
      return 0
    }
  }
}

// 数字转中文
export function chinanum (digit) {
  digit = typeof digit === 'number' ? String(digit) : digit
  const zh = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
  const unit = ['千', '百', '十', '']
  const quot = ['万', '亿', '兆', '京', '垓', '秭', '穰', '沟', '涧', '正', '载', '极', '恒河沙', '阿僧祗', '那由他', '不可思议', '无量', '大数']
  let breakLen = Math.ceil(digit.length / 4)
  let notBreakSegment = digit.length % 4 || 4
  let segment
  let zeroFlag = []
  let allZeroFlag = []
  let result = ''
  while (breakLen > 0) {
    if (!result) { // 第一次执行
      segment = digit.slice(0, notBreakSegment)
      let segmentLen = segment.length
      for (let i = 0; i < segmentLen; i++) {
        if (segment[i] !== 0) {
          if (zeroFlag.length > 0) {
            result += '零' + zh[segment[i]] + unit[4 - segmentLen + i]
            // 判断是否需要加上 quot 单位
            if (i === segmentLen - 1 && breakLen > 1) {
              result += quot[breakLen - 2]
            }
            zeroFlag.length = 0
          } else {
            result += zh[segment[i]] + unit[4 - segmentLen + i]
            if (i === segmentLen - 1 && breakLen > 1) {
              result += quot[breakLen - 2]
            }
          }
        } else {
          // 处理为 0 的情形
          if (segmentLen === 1) {
            result += zh[segment[i]]
            break
          }
          zeroFlag.push(segment[i])
          continue
        }
      }
    } else {
      segment = digit.slice(notBreakSegment, notBreakSegment + 4)
      notBreakSegment += 4
      for (let j = 0; j < segment.length; j++) {
        if (segment[j] !== 0) {
          if (zeroFlag.length > 0) {
            // 第一次执行zeroFlag长度不为0，说明上一个分区最后有0待处理
            if (j === 0) {
              result += quot[breakLen - 1] + zh[segment[j]] + unit[j]
            } else {
              result += '零' + zh[segment[j]] + unit[j]
            }
            zeroFlag.length = 0
          } else {
            result += zh[segment[j]] + unit[j]
          }
          // 判断是否需要加上 quot 单位
          if (j === segment.length - 1 && breakLen > 1) {
            result += quot[breakLen - 2]
          }
        } else {
          // 第一次执行如果zeroFlag长度不为0, 且上一划分不全为0
          if (j === 0 && zeroFlag.length > 0 && allZeroFlag.length === 0) {
            result += quot[breakLen - 1]
            zeroFlag.length = 0
            zeroFlag.push(segment[j])
          } else if (allZeroFlag.length > 0) {
            // 执行到最后
            if (breakLen === 1) {
              result += ''
            } else {
              zeroFlag.length = 0
            }
          } else {
            zeroFlag.push(segment[j])
          }
          if (j === segment.length - 1 && zeroFlag.length === 4 && breakLen !== 1) {
            // 如果执行到末尾
            if (breakLen === 1) {
              allZeroFlag.length = 0
              zeroFlag.length = 0
              result += quot[breakLen - 1]
            } else {
              allZeroFlag.push(segment[j])
            }
          }
          continue
        }
      }

      --breakLen
    }
    return result
  }
}

// 判断参数
export async function paramsShow (val, api, query) {
  const list = await api(query)
  var idShow = 0
  if (list) {
    for (var i = 0; i < list.length; i++) {
      if (val !== list[i].id) {
        idShow += 0
      } else {
        idShow += 1
      }
    }
  }
  return idShow
}
